import { Container, Box, TopicSelection, CurrentItem } from "./styled";
import { Collapse, Modal, RadioChangeEvent, Button, Radio } from "antd";
import Header from "@/componets/header";
import Choice from "@/componets/choice";
import React, { useEffect, useMemo, useState, useCallback } from "react";
import MulChoice from "@/componets/mulChoice";
import ShortAnswer from "@/componets/shortAnswer";
import { Question, getQuestion } from "@/api/question";
import { CheckboxValueType } from "antd/es/checkbox/Group";
import CodeAswer from "@/componets/code";
import { useLocation, useNavigate } from "react-router-dom";
import MarkDownComponent from "@/componets/markdown";

const { Panel } = Collapse;

const Practice = () => {
  const [data, setData] = useState<Question[]>([]);
  const [index, setIndex] = useState(0);
  const [answers, setAnswers] = useState<any[]>([]);
  const location = useLocation();
  const [isSumitted, setIsSumitted] = useState(false);
  const [isRights, setIsRights] = useState<boolean[]>([]);
  const navigate = useNavigate();

  const count = useMemo(() => data.length, [data]);

  const handleComeAgain = () => {
    const { questions, ...params } = location.state;
    getQuestion(params).then((res) => {
      setData(res);
      clear();
    });
  };

  useEffect(() => {
    console.log(location.state);
    const questions = location.state.questions;
    setData(questions);
    setAnswers(new Array(questions.length));
  }, []);

  const clear = () => {
    setIsRights([]);
    const copy = answers.slice().fill(null);
    setAnswers(copy);
    setIsSumitted(false);
    setIndex(0);
  };

  const handleQuestion = () => {
    if (canSumited) {
      if (isSumitted) {
        clear();
      } else {
        const idxs: number[] = [];
        for (let i = 0; i < count; i++) {
          if (!answers[i]) {
            idxs.push(i + 1);
          }
        }

        Modal.confirm({
          title: "是否确认提交",
          content: idxs.length > 0 ? "还剩第" + idxs + "没做完" : "",
          onOk: () => {
            const res = data
              .filter((x) => ["单选题", "多选题"].includes(x.type))
              .map((it, index) => it.answer === answers[index]);
            setIsRights(res);
            setIsSumitted(true);
          },
        });
      }
    } else setIndex((prev) => prev + 1);
  };

  const handleCheck = (idx: number, text: string | CheckboxValueType[]) => {
    const copy = JSON.parse(JSON.stringify(answers));
    copy[idx] = text;
    setAnswers(copy);
  };

  useEffect(() => {
    console.log(answers);
  }, [answers]);

  const canSumited = useMemo(() => index + 1 === data.length, [index, data]);

  return (
    <Container>
      <Header />
      <TopicSelection>
        {Array.from({ length: count }, (item, idx) => (
          <CurrentItem
            key={idx}
            actived={index === idx}
            onClick={() => setIndex(idx)}
            isSumitted={isSumitted}
            isRight={isRights[idx]}
          >
            {idx + 1}
          </CurrentItem>
        ))}
      </TopicSelection>
      <Box>
        {data.map((it, idx) => {
          const isActive = index === idx;
          const isRadioOrJudge = it.type === "单选题";
          const isMulChoice = it.type === "多选题";
          const isShortAnswer = it.type === "简答题";
          const isCode = it.type === "编程题";

          return (
            <React.Fragment key={it._id}>
              {isActive && isRadioOrJudge && (
                <Choice
                  index={idx + 1}
                  data={it}
                  value={answers[idx]}
                  handleCheck={(text) => handleCheck(idx, text)}
                />
              )}
              {isActive && isMulChoice && (
                <MulChoice
                  handleCheck={(text) => handleCheck(idx, text)}
                  index={idx + 1}
                  value={answers[idx]}
                  data={it}
                />
              )}
              {isActive && isShortAnswer && (
                <ShortAnswer
                  handleCheck={(text) => handleCheck(idx, text)}
                  value={answers[idx]}
                  index={idx + 1}
                  data={it}
                />
              )}
              {isActive && isCode && (
                <CodeAswer
                  handleCheck={(text) => handleCheck(idx, text)}
                  value={answers[idx]}
                  index={idx + 1}
                  data={it}
                />
              )}
            </React.Fragment>
          );
        })}
        <div
          style={{
            position: "absolute",
            display: "flex",
            justifyContent: "center",
            left: 0,
            right: 0,
            bottom: "15px",
            margin: "auto",
          }}
        >
          <Button type="primary" onClick={handleQuestion}>
            {canSumited ? (isSumitted ? "重做" : "提交") : "下一题"}
          </Button>
          {isSumitted && (
            <>
              <Button style={{ marginLeft: "10px" }} onClick={handleComeAgain}>
                再来一套
              </Button>
              <Button
                style={{ marginLeft: "10px" }}
                onClick={() => navigate("/home")}
              >
                返回首页
              </Button>
            </>
          )}
        </div>
      </Box>
      {isSumitted && (
        <AnswerText
          answer={data[index].answer}
          analysis={data[index].analysis}
        />
      )}
    </Container>
  );
};

const panelStyle = {
  marginBottom: 24,
  border: "none",
};

const AnswerText = ({
  answer,
  analysis,
}: {
  answer: string;
  analysis?: string;
}) => {
  return (
    <div
      style={{
        width: "50vw",
        margin: "10px auto",
        height: "40px",
        lineHeight: "40px",
        background: "#fff",
      }}
    >
      <Collapse bordered={false}>
        <Panel header="答案/解析" key="1" style={panelStyle}>
          <p>答案：</p>
          <MarkDownComponent text={answer} />
          {analysis && (
            <>
              <p>解析：</p>
              <MarkDownComponent text={analysis} />
            </>
          )}
        </Panel>
      </Collapse>
    </div>
  );
};

export default Practice;
